<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.official_name"
          placeholder="请输入名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-action="'official@create'"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button
          :disabled="selectedIds.length === 0"
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleBatchSync"
          :loading="batchSyncing"
        >全局同步({{ selectedIds.length }}/20)</el-button>

        <el-button
          :disabled="allList.length === 0"
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleBatchSyncAll"
          :loading="batchSyncing"
        >全部同步</el-button>
      </el-col>


    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      :row-key="row => row.id"
      @selection-change="handleSelectionChange">
      <el-table-column
        v-if="false"
        type="selection"
        :reserve-selection="true"
        width="55">
      </el-table-column>
      <el-table-column prop="id" label="ID" align="center" />
      <el-table-column prop="official_name" label="公众号名称" align="center" />
      <el-table-column prop="long_url" show-overflow-tooltip label="长链接" align="center" />
      <el-table-column prop="status" label="启用状态" align="center">
        <template v-slot="scoped">
          <el-tag v-if="scoped.row.status == '启用'" type="success">启用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-action="'official@remote'"
            size="mini"
            type="warning"
            @click="handleRemote(scope.row)"
            v-if="true"
          >同步
          </el-button>
          <el-button
            v-action="'official@update'"
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >修改
          </el-button>
          <el-button
            v-action="'official@delete'"
            size="mini"
            type="danger"
            @click="handleDel(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="handlePagination" />
    <!-- 新增/修改 -->
    <AddEdit :open.sync="open" :title="title" :form="form" @getList="getList" />
  </div>
</template>
<script>
import { deleteOfficial, officialList, remoteOfficial, batchSyncOfficials } from '@/api/basics'
import AddEdit from './AddEdit'
export default {
  name: 'Index',
  components: {
    AddEdit
  },
  data() {
    return {
      pid: 0,
      // 遮罩层
      loading: true,
      open: false,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      form: {},
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        name: undefined
      },
      show: false,
      selectedIds: [], // 存储选中的ID
      batchSyncing: false,
      isPageChange: false,
      allList: []
    }
  },
  computed: {
    // 计算所有选中的ID（用于显示）
    selectedIds() {
      return this.selectedIds
    }
  },
  created() {
    this.getList()
    this.getAllList()
  },
  methods: {
    //同步所有列表
    async handleBatchSyncAll() {
      if (this.allList.length === 0) {
        this.$message.warning('还没有公众号')
        return
      }

      //加一个确定按钮
      this.$confirm('确定要同步吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

      try {

        //用轮训单个同步的方法
        this.batchSyncing = true
        for (const item of this.allList) {
          const res = await remoteOfficial(item.id)
          //提示 公众号名称
          this.$message.success(`${item.official_name}同步成功`)
          //在用 notify
          this.$notify({
            title: '成功',
            message: `${item.official_name}同步成功`,
            type: 'success',
            duration: 0
          })
        }
        //用 notify 提示
        this.$notify({
          title: '成功',
          message: '批量同步全部完成',
          type: 'success'
        })
        this.getList()
      } catch (error) {
        this.$message.error('批量同步失败：' + error.message)
      } finally {
        this.batchSyncing = false
      }
      })
    },

    //获取所有公众号
    getAllList() {
      const that = this
      officialList({ page: 1, limit: 1000 }).then(response => {
        if (response.code === 10000) {
          that.allList = response.data
        }
      })
    },
    handleRemote(row) {
      const that = this
      this.loading = true
      remoteOfficial(row.id).then(response => {
        if (response.code === 10000) {
          that.loading = false

          if (response.data.count > 0) {
            that.$notify({
              title: '成功',
              type: 'success',
              message: `${response.data.count}条新闻同步成功。`
            })
          } else {
            that.$notify.info({
              title: '成功',
              message: '公众号无最新内容'
            })
          }
        }
      })
    },
    /** 查询列表 */
    getList() {
      console.log('当前选中的IDs:', this.selectedIds)
      this.isPageChange = true
      const that = this
      this.loading = true
      officialList(this.queryParams).then(response => {
        if (response.code === 10000) {
          that.list = response.data
          that.total = response.count
          that.loading = false
        }
        this.isPageChange = false
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form = {
        status: '启用'
      }
      this.open = true
      this.title = '添加'
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.form = row
      this.open = true
      this.title = '编辑'
    },
    /** 删除按钮操作 */
    handleDel(row) {
      const that = this
      that.$confirm('是否要删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        that.loading = true
        deleteOfficial(row.id).then(response => {
          that.loading = false
          if (response.code === 10000) {
            that.$message.success(response.message)
            that.getList()
          } else {
            that.$message.error(response.message)
          }
        })
      }).catch(() => {
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.selectedIds = []
      this.queryParams = {
        page: 1,
        limit: 10,
        account_code: undefined,
        account_name: undefined
      }
      this.handleQuery()
    },
    handleSelectionChange(val) {
      // 如果选中数量超过20个
      if (val.length > 20) {
        this.$message.warning('最多只能选择20个公众号，已自动保留最后20个选中项')

        // 获取需要保留的最后20个选中项
        const keepRows = val.slice(-20)

        // 清除所有选中状态
        this.$refs.table.clearSelection()

        // 重新选中最后20个
        this.$nextTick(() => {
          keepRows.forEach(row => {
            this.$refs.table.toggleRowSelection(row, true)
          })
        })

        // 更新选中的ID
        this.selectedIds = keepRows.map(row => row.id)
      } else {
        // 正常更新选中的ID
        this.selectedIds = val.map(row => row.id)
      }
    },
    async handleBatchSync() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请选择要同步的公众号')
        return
      }

      //加一个确定按钮
      this.$confirm('确定要同步吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {

      try {

        //用轮训单个同步的方法
        this.batchSyncing = true
        for (const id of this.selectedIds) {
          const res = await remoteOfficial(id)
          //提示 公众号名称
          this.$message.success(`${res.data.name}同步成功`)
        }
        //用 notify 提示
        this.$notify({
          title: '成功',
          message: '批量同步全部完成',
          type: 'success'
        })
        this.getList()
      } catch (error) {
        this.$message.error('批量同步失败：' + error.message)
      } finally {
        this.batchSyncing = false
      }
      })
    },
    // 翻页处理
    handlePagination() {
      this.getList()
    }
  }
}

</script>

